from flask_restful.reqparse import RequestParser
from info.index import index_bp
from flask import render_template, request, redirect, jsonify
from model import *
from flask_login import current_user, logout_user, login_required


@index_bp.route('/students')
def index_students():
    # 分页信息获取
    page = request.args.get('page', type=int, default=1)
    limit = request.args.get('limit', type=int, default=10)
    # nonlocal students
    count = Student.query.count()
    students = Student.query.paginate(page, limit, False).items
    students_list = [{'id': item.id, 'name': item.name,
                      'chinese': item.chinese, 'math': item.math,
                      'english': item.english, 'average_score': round((item.chinese + item.math + item.english) / 3, 1)}
                     for item in students]
    # print(students)
    ret = {"code": 0, "message": "", "count": count, "data": students_list, 'success': True}
    print('ret', ret)
    return jsonify(ret)


@index_bp.route('/change', methods=['GET', 'POST'])
def change():
    if request.method == 'POST':
        parser = RequestParser()
        password = current_user.password
        parser.add_argument('username', location='form')
        parser.add_argument('old_password', location='form')
        parser.add_argument('new_password', location='form')
        res = parser.parse_args()
        if password != res.old_password:
            return render_template('change_password/修改密码-错误弹窗.html')
        else:
            current_user.username = res.username
            current_user.password = res.new_password
            db.session.commit()
            return render_template('change_password/修改密码-正确弹窗.html')
    return render_template('change_password/修改密码.html')


@index_bp.route('/exit_user')
def exit_user():
    logout_user()
    return redirect('/auth/login')


@index_bp.route('/add', methods=['GET', 'POST'])
def add():
    if request.method == 'POST':
        student = Student(**{
            'name': request.form.get('name'),
            'chinese': request.form.get('chinese', type=int),
            'math': request.form.get('math', type=int),
            'english': request.form.get('english', type=int)
        })
        db.session.add(student)
        db.session.commit()
        return redirect('/admin')
    return render_template('admin/录入.html')


@index_bp.route('/delete')
def delete():
    name = request.args.get('name')
    student = Student.query.filter_by(name=name).first()
    db.session.delete(student)
    db.session.commit()
    return redirect('/admin')


@index_bp.route('/change_table', methods=['GET', 'POST'])
def change_table():
    id_ = request.args.get('id', type=int)
    student = Student.query.get(id_)
    if request.method == 'GET':
        return render_template('admin/修改.html', student=student)
    parser = RequestParser()
    parser.add_argument('name', location='form')
    parser.add_argument('chinese', location='form', type=int)
    parser.add_argument('math', location='form', type=int)
    parser.add_argument('english', location='form', type=int)
    args = parser.parse_args()
    student.name = args.name
    student.chinese = args.chinese
    student.math = args.math
    student.english = args.english
    print(student)
    db.session.commit()
    return {'code': 0, 'success': True}


@index_bp.route('/')
def main():
    return redirect('/auth/login')


@index_bp.route('/admin')
@login_required
def admin():
    return render_template('admin/主页面.html')


@index_bp.route('/admin_personal')
@login_required
def admin_personal():
    return render_template('information/个人信息.html')


@index_bp.route('/admin_information', methods=['GET', 'POST'])
@login_required
def admin_information():
    """
    username,    password ,  city ,hobby ,  sex ,text ,
    :return:
    """
    if request.method == 'POST':
        parser = RequestParser()
        parser.add_argument('username', location='form')
        parser.add_argument('password', location='form')
        parser.add_argument('city', location='form')
        parser.add_argument('hobby', location='form')
        parser.add_argument('sex', location='form')
        parser.add_argument('text', location='form')
        res = parser.parse_args()
        for k, v in res.items():
            setattr(current_user, k, v)
        return redirect('/admin')
    return render_template('information/设置个人信息.html')
